from datetime import datetime
from typing import Optional
from fastapi import APIRouter, Query
from apps.schemas.schemas import StudentCreateRequest, StudentUpdateRequest
from apps.services.student import (
    get_all_students,
    get_student_by_user_id,
    get_student_by_id,
    create_student,
    update_student,
    delete_student
)
from apps.deps.JWT import require_role

students = APIRouter()


@require_role('STUDENT')
@students.get("/msg")
async def get_all_students_api(
        username: Optional[str] = Query(None, alias="username"),
        page: int = Query(1, ge=1),
        page_size: int = Query(10, ge=1, le=100)
):
    """
    获取所有学生列表（分页）
    """
    try:
        total, students_data = await get_all_students(username, page, page_size)
        return {
            "status": 200,
            "message": "success",
            "data": students_data,
            "total": total,
            "page": page,
            "page_size": page_size
        }
    except Exception as e:
        return {
            "status": 500,
            "message": f"Error retrieving students: {str(e)}",
            "data": [],
            "total": 0,
            "page": page,
            "page_size": page_size
        }


@students.get("/msg/userId/{user_id}")
async def get_student_by_user_id_api(user_id: int):
    """
    根据用户ID获取学生信息
    """
    try:
        student_data = await get_student_by_user_id(user_id)
        if student_data:
            return {
                "status": 200,
                "message": "success",
                "data": student_data
            }
        else:
            return {
                "status": 404,
                "message": "Student not found",
                "data": {}
            }
    except Exception as e:
        return {
            "status": 500,
            "message": f"Error retrieving student: {str(e)}",
            "data": {}
        }


@students.get("/msg/{student_id}")
async def get_student_api(student_id: int):
    """
    根据学生ID获取学生信息
    """
    try:
        student_data = await get_student_by_id(student_id)
        if student_data:
            return {
                "status": 200,
                "message": "success",
                "data": student_data
            }
        else:
            return {
                "status": 404,
                "message": "Student not found",
                "data": {}
            }
    except Exception as e:
        return {
            "status": 500,
            "message": f"Error retrieving student: {str(e)}",
            "data": {}
        }


@students.post("/add")
async def create_student_api(data: StudentCreateRequest):
    """
    创建新的学生
    """
    try:
        await create_student(data)
        return {
            "status": 201,
            "message": "Student created successfully",
            "data": {}
        }
    except ValueError as e:
        return {
            "status": 400,
            "message": str(e),
            "data": {}
        }
    except Exception as e:
        return {
            "status": 500,
            "message": f"Error creating student: {str(e)}",
            "data": {}
        }


@students.put("/update/{student_id}")
async def update_student_api(student_id: int, data: StudentUpdateRequest):
    """
    更新学生信息
    """
    try:
        updated = await update_student(student_id, data)
        if updated:
            return {
                "status": 200,
                "message": "Student updated successfully",
                "data": {}
            }
        else:
            return {
                "status": 404,
                "message": "Student not found",
                "data": {}
            }
    except ValueError as e:
        return {
            "status": 400,
            "message": str(e),
            "data": {}
        }
    except Exception as e:
        return {
            "status": 500,
            "message": f"Error updating student: {str(e)}",
            "data": {}
        }


@students.delete("/delete/{student_id}")
async def delete_student_api(student_id: int):
    """
    删除学生
    """
    try:
        deleted = await delete_student(student_id)
        if deleted:
            return {
                "status": 200,
                "message": "Student deleted successfully",
                "data": {}
            }
        else:
            return {
                "status": 404,
                "message": "Student not found",
                "data": {}
            }
    except Exception as e:
        return {
            "status": 500,
            "message": f"Error deleting student: {str(e)}",
            "data": {}
        }
